package cn.im.qywx.controller;

import cn.im.qywx.queue.TokenQueue;
import cn.im.qywx.service.ImWxMeetingService;
import cn.im.qywx.system.SystemParams;
import cn.im.qywx.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;


/**
 * 会议室预约
 */
@Slf4j
@Controller
@RequestMapping("/meeting")
public class MeetingController {

    @Resource
    ImWxMeetingService meetingService;

    @Autowired
    RestTemplate restTemplate;

    @GetMapping
    public String index(HttpServletRequest request,Model model, String code, String state){

       log.info("user:{} code:{}  ",request.getSession().getAttribute("meeting_wxno"),code);

       String rooms="[]";
       String reserve="[]";
       String departments="[]";
       String isError="";

        //若用户已登录，不需要再校验
        if(request.getSession().getAttribute("meeting_wxno")!=null){
            //获取会议室列表
            rooms=JsonUtils.obj2json(meetingService.getMeetingRoomList());
            //获取会议预定数据列表
            reserve=JsonUtils.obj2json(meetingService.getWeekReserveList());
            //获取部门成员列表
            departments= JsonUtils.obj2json(SystemParams.departments);

        }else {
            //获取用户信息
            Map<String,String> map = null;
            for(int i=0; i<2; i++){
                //通过code获取用户信息
                String url = SystemParams.URL_USER+"getuserinfo?code="+code+"&access_token="+TokenQueue.getToken(SystemParams.AGENTID_MEETING);
                map = JsonUtils.json2MapSingleStr(restTemplate.getForObject(url,String.class));
                if(map!=null){
                    if("0".equals(map.get("errcode"))){
                        url = SystemParams.URL_USER+"get?access_token="+ TokenQueue.getToken(SystemParams.AGENTID_MEETING)+"&user_ticket="+map.get("user_ticket")+"&UserId="+map.get("UserId");
                        Map<String,Object> userInfo = JsonUtils.json2Map(restTemplate.getForObject(url,String.class));
                        if(userInfo==null){
                            map.put("errcode", "获取用户信息失败");
                        }else if(0==Math.round(Float.parseFloat(userInfo.get("errcode")+"")) && userInfo.get("name")!=null){
                            map.put("name", String.valueOf(userInfo.get("name")));
                        }else{
                            map.put("errcode", Math.round(Float.parseFloat(userInfo.get("errcode")+""))+"");
                        }
                    }

                    if(!"42001".equals(map.get("errcode")))
                        break;
                }
            }

            log.info("验证结果：{}",JsonUtils.obj2json(map));

            if(map!=null && "0".equals(map.get("errcode"))){
                String userId = map.get("UserId");
                String name = map.get("name");
                //存入用户
                request.getSession().setAttribute("meeting_wxno", userId);
                request.getSession().setAttribute("meeting_userName", name);

                rooms=JsonUtils.obj2json(meetingService.getMeetingRoomList());
                reserve=JsonUtils.obj2json(meetingService.getWeekReserveList());
                departments= JsonUtils.obj2json(SystemParams.departments);
            }else{
                isError = map==null?"nullMap":map.get("errcode");
            }
        }

        model.addAttribute("rooms", rooms);
        model.addAttribute("reserve", reserve);
        model.addAttribute("departments", departments);
        model.addAttribute("toDay", System.currentTimeMillis());
        model.addAttribute("isError", isError);

        return "meeting";
    }

    /** 新增会议预定
     */
    @ResponseBody
    @RequestMapping(value="/addMeeting")
    public String addMeeting(HttpServletRequest request, int roomId, String date, int startTime, int endTime, String topic, String users){
        HttpSession session = request.getSession();
        return JsonUtils.obj2json(meetingService.addReserve(roomId,(String)session.getAttribute("meeting_wxno"),(String)session.getAttribute("meeting_userName"),date,startTime,endTime,topic,users));
    }

    /** 取消会议预定
     */
    @ResponseBody
    @RequestMapping(value="/cancelMeeting")
    public String cancelMeeting(int id,HttpSession session){
        return JsonUtils.obj2json(meetingService.cancelReserve(id,(String)session.getAttribute("meeting_wxno")));
    }
}
